﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using SMSSnew.DATA;
using Telerik.WebControls.Base.Calendar;

namespace SMSSnew.UI.teacher
{
    public partial class SpecialMedical : System.Web.UI.Page
    {
        public static string userName;
        LeaveApplicationListDA leaveAppList = new LeaveApplicationListDA();
        LeaveApplicationDA leaveApp = new FullDayLeaveDA();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                userName = Session["username"].ToString();
                setAvailablePendingLeavesInLabels();
                radDpFrom.SelectedDates.Clear();
            }
        }

        //ok can be used for half/short/special
        protected void setAvailablePendingLeavesInLabels()
        {
            DateTime currentDate = new DateTime();
            currentDate = DateTime.Now;
            string numOfLeaves;

            numOfLeaves = leaveAppList.countAvailableAndPendingForSpecialMedical(userName);
            string[] amountOfLeaves = numOfLeaves.Split(new string[] { "," }, StringSplitOptions.None);

            lblAvailMedicalCurrent.Text = (Math.Truncate(Double.Parse(amountOfLeaves[0]))).ToString();
            lblPendMedicalCurrent.Text = (Math.Truncate(Double.Parse(amountOfLeaves[1]))).ToString();
            lblAvailMedicalBeforeOne.Text = (Math.Round(Double.Parse(amountOfLeaves[2]))).ToString();
            lblAvailMedicalBeforeTwo.Text = (Math.Round(Double.Parse(amountOfLeaves[3]))).ToString();
         

            lblYearCurrent.Text = currentDate.Year.ToString();
            lblYearBeforeOne.Text = (currentDate.Year - 1).ToString();
            lblYearBeforeTwo.Text = (currentDate.Year - 2).ToString();

            lblYearCurrentReq.Text = currentDate.Year.ToString();
            lblYearBeforeOneReq.Text = (currentDate.Year - 1).ToString();
            lblYearBeforeTwoReq.Text = (currentDate.Year - 2).ToString();
        }

        protected void setValuesToLeaveApp()
        {
            DateTime start = new DateTime();
            DateTime end = new DateTime();

            sortSelectedDaysOfCalendar();
            start = radDpFrom.SelectedDate.Date;

            for (int i = 0; i < radDpFrom.SelectedDates.Count; i++)
            {
                end = (radDpFrom.SelectedDates[i]).Date;
            }

            leaveApp.setStartDate(start);
            leaveApp.setTeacherID(userName);
            leaveApp.setEndDate(end);
            leaveApp.setDuration(Double.Parse( countDurationBetweenTwoDays().ToString()));
            leaveApp.setReason(txtReason.Text);
            leaveApp.setStatus(0);
            leaveApp.setLeaveID("");
            leaveApp.setleaveCategoryId("SPECIAL");
            leaveApp.setAbsentTimePeriod("7.30-1.30");
            leaveApp.setleaveTypeId("MED");

        }

        // have to sort selected dates by the user
        protected void sortSelectedDaysOfCalendar()
        {
            DateTime temp = new DateTime();

            for (int pass = 1; pass <= radDpFrom.SelectedDates.Count - 1; pass++)
            {
                for (int i = 0; i <= radDpFrom.SelectedDates.Count - 2; i++)
                {
                    if ((radDpFrom.SelectedDates[i]).Date > (radDpFrom.SelectedDates[i + 1]).Date)
                    {
                        temp = (radDpFrom.SelectedDates[i + 1].Date);
                        (radDpFrom.SelectedDates[i + 1].Date) = (radDpFrom.SelectedDates[i].Date);
                        (radDpFrom.SelectedDates[i].Date) = temp;

                    }
                }
            }
        }

        protected void imgBtnBack_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("LeaveHome.aspx");
        }

        protected void lnkBtnLogout_Click(object sender, EventArgs e)
        {
            Response.Redirect("LeaveHome.aspx");
        }

        protected void lnkButSummary_Click(object sender, EventArgs e)
        {
            Response.Redirect("LeaveHome.aspx");
        }

      
        protected void radDpFrom_HeaderCellRender(object sender, Telerik.Web.UI.Calendar.HeaderCellRenderEventArgs e)
        {
            string columnName = e.Cell.Text;
            // the name of the column depends of the calendar Culture and the set DayNameFormat 
            if (columnName == "S")
            {
                e.Cell.Style["display"] = "none";
            }
        }

        protected void radDpFrom_DayRender(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
        {
            if (e.Day.IsWeekend)
            {
                e.Cell.Style["display"] = "none";
            }
        }

 
        // validate requesting duration contains any earlier requested dates
        protected string validateSpecialMedDurationHasEarlyRequests()
        {
            DateTime start = new DateTime();
            DateTime end = new DateTime();

            sortSelectedDaysOfCalendar();
            start = radDpFrom.SelectedDate.Date;

            for (int i = 0; i < radDpFrom.SelectedDates.Count; i++)
            {
                end = (radDpFrom.SelectedDates[i]).Date;
            }

            string message = leaveApp.validateSpecialMedDurationHasEarlyRequests(start, end, userName);
            return message;
        }

        // count duration between two days
        protected int countDurationBetweenTwoDays()
        {
            DateTime start = new DateTime();
            DateTime end = new DateTime();

            sortSelectedDaysOfCalendar();
            start = radDpFrom.SelectedDate.Date;

            for (int i = 0; i < radDpFrom.SelectedDates.Count; i++)
            {
                end = (radDpFrom.SelectedDates[i]).Date;
            }

          //  string message = leaveApp.countDurationBetweenTwoDays(start, end, userName).ToString();
            return leaveApp.countDurationBetweenTwoDays(start, end, userName);
        }

        protected void radDpFrom_SelectionChanged(object sender, Telerik.Web.UI.Calendar.SelectedDatesEventArgs e)
        {
            string message;
            DateTime date = new DateTime();

            // to set the last selected date for the validations - ok
            for (int i = 0; i < e.SelectedDates.Count; i++)
            {
                date = (e.SelectedDates[i]).Date;
            }
          
            // validate selected date is greater than today - ok
            if (leaveApp.validateRequstedDateGreaterThanToday(date) != "")
            {
                message = leaveApp.validateRequstedDateGreaterThanToday(date);
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + message + "');", true);
                radDpFrom.SelectedDates.Clear();
            }
            // validate whether requesting more than two days - ok
            else if (countDurationBetweenTwoDays() < 3)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Please request more than two day duration.');", true);
                // radDpFrom.SelectedDates.Clear();
            }
            // validate whether requesting period contains already requested days
            else if (validateSpecialMedDurationHasEarlyRequests() != "")
            {
                message = validateSpecialMedDurationHasEarlyRequests();
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + message + "');", true);
                radDpFrom.SelectedDates.Clear();
            }

        }

        protected void butSubmit_Click(object sender, EventArgs e)
        {
            // validate whether the form is filled or not
            if (radDpFrom.SelectedDates.Count != 2)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Please fill the form correctly');", true);
            }
            else if (RadNumericCurrent.Value > (Int32.Parse(lblAvailMedicalCurrent.Text) + Int32.Parse(lblPendMedicalCurrent.Text)) || RadNumericBeforeOne.Value > Int32.Parse(lblAvailMedicalBeforeOne.Text) || RadNumericBeforeTwo.Value > Int32.Parse(lblAvailMedicalBeforeTwo.Text))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('You are exceeding leaves offering! Please Try again.');", true);
                clearAll();
            }
            else if (countDurationBetweenTwoDays() != (RadNumericCurrent.Value + RadNumericBeforeOne.Value + RadNumericBeforeTwo.Value + RadNumericNopay.Value))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Duration and Requesting leave count is not matching! Please Try again.');", true);
                clearAll();
            }
            else
            {
                setValuesToLeaveApp();
                leaveApp.addLeaveToDB(leaveApp);
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Requesting is successfull');", true);
                Response.Redirect("LeaveHome.aspx");
                clearAll();
            }
        }

        protected void clearAll()
        {
            radDpFrom.SelectedDates.Clear();
            txtReason.Text = "";
            setAvailablePendingLeavesInLabels();
            RadNumericBeforeOne.Value = 0;
            RadNumericBeforeTwo.Value = 0;
            RadNumericCurrent.Value = 0;
            RadNumericNopay.Value = 0;
            FileUploadMdical.HasFile.Equals(false);
        }
    }
}
